package com.jp.knowledge.my.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.my.util.MyUtil;

import org.xutils.view.annotation.ViewInject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 528787067@qq.com on 2017/2/13.
 */

public class UserSettingEditActivity extends SlidingActivity implements View.OnClickListener {

	public static final int REQUEST_CODE = 0xFF;
	public static final String VIEW_ID = "id";
	public static final String RESULT_DATA = "resultData";
	private static final String EDIT_TITLE = "title";
	private static final String EDIT_CONTENT = "content";
	private static final String EDIT_HINT = "hint";
	private static final String INPUT_TYPE = "inputType";

	public static final int TYPE_STRING = 1;
	public static final int TYPE_INT = 2;
	public static final int TYPE_MAIL = 3;
	public static final int TYPE_DATE = 4;
	public static final int TYPE_NAME = 5;
	public static final int TYPE_PHONE = 6;
	public static final int TYPE_WEB = 7;

	public static void gotoEdit(Activity activity, int viewId, String title, String content, String hint) {
		gotoEdit(activity, viewId, title, content, hint, TYPE_STRING);
	}

	public static void gotoEdit(Activity activity, int viewId, String title, String content, String hint, int inputType) {
		Intent intent = new Intent(activity, UserSettingEditActivity.class);
		intent.putExtra(EDIT_TITLE, title);
		intent.putExtra(EDIT_CONTENT, content);
		intent.putExtra(EDIT_HINT, hint);
		intent.putExtra(VIEW_ID, viewId);
		intent.putExtra(INPUT_TYPE, inputType);
		activity.startActivityForResult(intent, REQUEST_CODE);
	}

	private Intent intent;
	private String title;
	private String content;
	private String hint;
	private int inputType;

	@ViewInject(R.id.position_edit_tv)
	private EditText editText;
	@ViewInject(R.id.edit_remind)
	private TextView remindText;

	private CommDialog userNameRemindDialog;

	@Override
	protected int getResourceId() {
		return R.layout.activity_position;
	}

	@Override
	protected void init() {
		this.intent = getIntent();
		this.title = intent.getStringExtra(EDIT_TITLE);
		this.content = intent.getStringExtra(EDIT_CONTENT);
		this.hint = intent.getStringExtra(EDIT_HINT);
		this.inputType = intent.getIntExtra(INPUT_TYPE, TYPE_STRING);
		userNameRemindDialog = new CommDialog(mContext);
		userNameRemindDialog.setContent("你确认保存，保存后将不能修改？");
		userNameRemindDialog.setRightListener(this);
		switch (inputType){
			case TYPE_INT:
			case TYPE_DATE:
				editText.setInputType(InputType.TYPE_CLASS_NUMBER);
				break;
			case TYPE_PHONE:
				editText.setInputType(InputType.TYPE_CLASS_PHONE);
				break;
		}
		initView();
	}

	@Override
	protected void onStart() {
		super.onStart();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				MyUtil.startKeyword(UserSettingEditActivity.this, editText);
			}
		}, 300);
	}

	private void initView() {
		topName.setText(title == null ? "" : title);
		editText.setText(content == null ? "" : content);
		editText.setHint(hint == null ? "" : hint);
		leftIcon.setImageResource(R.mipmap.arrow_white_left);
		topDesc.setVisibility(View.GONE);
		rightIcon.setVisibility(View.GONE);
		rightBtn.setVisibility(View.VISIBLE);
		rightBtn.setText("保存");
		editText.setSelection(editText.getText().length());
		leftIcon.setOnClickListener(this);
		rightBtn.setOnClickListener(this);
		editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					onClick(rightBtn);
				}
				return true;
			}
		});
		if (title != null && title.contains("姓名")) {
			remindText.setVisibility(View.VISIBLE);
		}
	}

	private void finishSelf() {
		MyUtil.closeKeyword(UserSettingEditActivity.this, editText);
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				finish();
			}
		}, 300);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.icon_left:
				finishSelf();
				break;
			case R.id.right_bn:
				String text = editText.getText().toString().trim();
				if (text.length() == 0)
					ToasUtil.toast(this, "抱歉，请输入有效的数据后再确定");
				else if (inputType == TYPE_INT && !isNum(text))
					ToasUtil.toast(this, "请输入有效整数数值");
				else if (inputType == TYPE_MAIL && !isEmail(text))
					ToasUtil.toast(mContext, "请输入正确的邮箱");
				else if (inputType == TYPE_NAME && !text.equals(content))
					userNameRemindDialog.show();
				else if (inputType == TYPE_DATE && !isTimeCorrent(text))
					ToasUtil.toast(mContext, "时间格式不正确");
				else if (inputType == TYPE_WEB && !isWebUrl(text))
					ToasUtil.toast(mContext, "请输入正确的网址");
				else
					editFinish(text);
					break;
			case R.id.right_btn:
				editFinish(editText.getText().toString().trim());
				break;
		}
	}

	private void editFinish(String result) {
		intent.putExtra(RESULT_DATA, result);
		setResult(RESULT_OK, intent);
		finishSelf();
	}

	private boolean isNum(String num){
		try{
			Integer.parseInt(num);
			return true;
		} catch (Exception e){
			return false;
		}
	}

	private boolean isWebUrl(String url){
		try{
			Pattern phonePattern = Pattern.compile("^(http(s)?:\\/\\/)?(www\\.)?[\\w-]+\\.\\w{2,4}(\\/)?$");
			Matcher matcher = phonePattern.matcher(url);
			return matcher.find();
		} catch (Exception e) {
			return false;
		}
	}

	private boolean isEmail(String email) {
		try {
			Pattern emailPattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
			Matcher matcher = emailPattern.matcher(email);
			return matcher.find();
		} catch (Exception e) {
			return false;
		}
	}

	private boolean isTimeCorrent(String time) {
		if (time.trim().length() != 14)
			return false;
		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss", Locale.getDefault());
			dateFormat.parse(time);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
